<!--
 * @Author: XieQiu 雪球
 * @Date: 2021-05-10 15:07:49
 * @LastEditTime: 2023-07-10 09:36:35
 * @LastEditors: Please set LastEditors
 * @Description: 设施分组管理页面
-->
<template>
  <BaseMainSlot :show-tab="true">
    <template v-slot:btn-box>
      <ActionBar
        :page-no="48"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :has-cancel="false"
        :has-save="false"
        :has-edit="false"
        @add="add"
        @cancel="cancel('formData')"
        @edit="edit"
        @del="del"
        @save="save('formData')"
      />
    </template>
    <template v-slot:tab-select>
      <SelectButton @topitemtype="topitemtype" />
    </template>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
      <!-- <SearchBox @search="search">
        <div class="common-search-item">
          <div class="label">设施组名称:</div>
          <div class="input">
            <el-input v-model="facilityGroupName" placeholder="请输入设施组名称" clearable />
          </div>
        </div>
        <div class="common-search-item">
          <div class="label">承租户:</div>
          <div class="input">
            <el-select v-model="lesseeNo" filterable clearable @change="search()">
              <el-option
                v-for="item in lesseeList"
                :key="item.lesseeNo"
                :label="item.lesseeName"
                :value="item.lesseeNo"
              />
            </el-select>
          </div>
        </div>
      </SearchBox> -->
    </template>
    <template v-slot:table-box>
      <el-table
        ref="tableData"
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="calc(100% - 50px)"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="facilityGroupName" label="设施组名称" />
        <!-- <el-table-column prop="lessee" label="承租户">
          <template v-if="scope.row.facilityGroupNo" slot-scope="scope">
            <div v-if="scope.row.lessee">{{ scope.row.lessee }}</div>
            <div v-else>——</div>
          </template>
        </el-table-column>-->
        <el-table-column prop="facilityBOList" label="设施名称">
          <!-- <template
            v-if="tableScope.row.facilityBOList"
            slot-scope="tableScope"
          >
            <div
              v-for="(item, index) in tableScope.row.facilityBOList"
              :key="index"
            >
              <span v-if="item !== null">{{ item.facilityName || "无" }}</span>
              <span v-else>——</span>
          </div>-->
          <!-- </template> -->
          <template v-if="scope.row.facilityGroupNo" slot-scope="scope">
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="seeEquip(scope.row)"
            >
              <i class="el-icon-view"></i> 查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="是否历史设施组" min-width="65">
          <template v-if="scope.row.facilityGroupNo" slot-scope="scope">
            <span>
              <!-- :disabled="topitemtypeid === 1 ? false : true" -->
              <el-switch
                v-model="scope.row.groupStatus"
                :active-value="true"
                :inactive-value="false"
                @change="faciStatus(scope.row)"
              />
            </span>
          </template>
        </el-table-column>
        <el-table-column v-if="topitemtypeid == false" width="120" label="操作">
          <template v-if="scope.row.facilityGroupNo" slot-scope="scope">
            <el-button
              v-if="judgePermission(48, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="handleEdit(scope.row)"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-if="judgePermission(48, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(scope.row)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="dialogTitle + '设施分组信息'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
        width="40%"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="设施组名称:" prop="facilityGroupName" class="w100p">
            <el-input v-model="formData.facilityGroupName" placeholder="请输入设施组名称" clearable />
          </el-form-item>
          <el-form-item label="所包含设施:" class="w100p">
            <div class="facility_arr">
              <div v-if="!aboutFacilityArr[0]" class="facility_title">请在下方选择设施</div>
              <div class="tags">
                <div v-for="item in aboutFacilityArr" :key="item.facilityNo" class="tag-item">
                  <div class="point-name">{{ item.facilityName }}</div>
                  <div class="close">
                    <i class="el-icon-circle-close" @click="removeFacilityTag(item.facilityNo)"></i>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="设施列表:" class="w100p">
            <el-input v-model="facilityName" clearable @input="searchFacility" />
          </el-form-item>
          <div class="tags">
            <div
              v-for="item in facilityArr"
              :key="item.facilityNo"
              class="tag-item"
              @click="addFacilityTag(item)"
            >
              <div class="point-name">{{ item.facilityName }}</div>
            </div>
          </div>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
      <SeeEquip
        :is-show-equip="isShowEquip"
        :equip-data="facilityBOList"
        @closeDialog="isShowEquip = false"
      />
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import divideInfoManage from "@/api/digital-operation/land-manage/divide-manage";
import landgroupInfoManage from "@/api/digital-operation/land-manage/land-group-manage";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import SelectButton from "../components/selcetButton/selcetButtons.vue";
import SeeEquip from "@/components/seeEquip/index.vue";
import { mymixin } from "@/utils/mixin";
import { mapGetters } from "vuex";
export default {
  name: "LandGroupManage",
  components: {
    SearchForm,
    ActionBar,
    Pagination,
    BaseMainSlot,
    SelectButton,
    SeeEquip
  },
  mixins: [mymixin],
  data() {
    return {
      formConfig: [
        {
          label: '设施组名称',
          prop: 'facilityGroupName',
          type: 'input',
        }, {
          label: '承租户',
          prop: 'lesseeNo',
          type: 'select',
          options: [], // lesseeList
          optionKey: { label: 'lesseeName', value: 'lesseeNo' },
        },
      ],
      searchlist: {},
      obj: {
        name: ""
      },
      facilityGroupNoList: [],
      // 土地名称
      facilityNo: "",
      facilityName: "",
      lessee: "",
      // 设施组名称
      facilityGroupName: "",
      topitemtypeid: "",
      // 包含田块数组
      aboutFacilityArr: [],
      isShowEquip: false,
      facilityBOList: [],
      // 田块数组
      facilityArr: [],
      lesseeList: [],
      lesseeNo: [],
      // 选中的数据项数组 ID组成
      facilityNoList: [],
      rules: {
        facilityGroupName: [
          { required: true, message: "请输入设施组名称", trigger: "blur" }
        ]
      },
      dialogTitle: "",
      dialogFormVisible: false
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {},
  created() {
    // 获取所有可以添加设施
    // this.searchFacility();
  },
  mounted() {
    this.selectlist();
    // // 获取表格数据
    // this.search();
  },
  methods: {
    async seeEquip(row) {
      console.log("a");
      // this.facilityBOList = row.facilityBOList

      // console.log(this.isShowEquip);
      // console.log(row.facilityBOList);
      const { data: resp } = await landgroupInfoManage.queryFacilityGroup(
        row.facilityGroupNo
      );
      // console.log(resp);
      if (resp !== undefined && resp.length > 0) {
        this.isShowEquip = true;
        this.facilityBOList = resp;
      } else {
        this.$message.warning("暂无设施");
      }
    },
    async selectlist() {
      divideInfoManage.queryLessesByCondition().then(res => {
        this.lesseeList = res.data;
        this.formConfig[1].options = res.data;
      });
    },
    // 获取点击的分页index
    topitemtype(e) {
      this.topitemtypeid = e;
      // 获取表格数据
      this.formData = {};
      this.tableData = [];
      this.facilityGroupName = "";
      this.lessee = "";
      this.currentPage = 1;
      this.search();
    },
    // 获取表格数据
    getTableDataList() {
      this.loading = true;
      // this.tableData = [];
      // this.formData = {};
      // 包含田块数组
      this.aboutFacilityArr = [];
      // 田块数组
      this.facilityArr = [];
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          facilityGroupName: this.searchlist.facilityGroupName || undefined,
          groupStatus: this.topitemtypeid,
          lesseeNo: this.searchlist.lesseeNo || undefined
        }
      };
      landgroupInfoManage.getLandGroupList(params).then(res => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.totalSize = data.totalElements;
          data.content.forEach(item => {
            if (item.groupStatus === 1) {
              item.groupStatus = "1";
              // console.log(item.facilityStatus)
            } else if (item.groupStatus === 2) {
              item.groupStatus = "2";
              // console.log(item.facilityStatus)
            }
          });
          this.tableData = data.content;
          this.addblankmet();
          this.searchFacility();
          this.resetActionBar();
        }
      });
    },
    // 查询未分配设施名称
    searchFacility() {
      this.facilityArr = [];
      this.isDistribution = false;
      let params = {
        // organizationList: sessionStorage.organizationList,
        isDistribution: this.isDistribution
      };
      params["facilityName"] = this.facilityName;
      params["facilityStatus"] = false;
      params["organizationNo"] = sessionStorage.organizationNo;
      divideInfoManage.getFacilityListByConditionAll(params).then(res => {
        let data = res.data;
        this.facilityArr = data;
      });
    },
    // 添加田块tag
    addFacilityTag(item) {
      if (!this.canInput) {
        return;
      } else {
        if (this.aboutFacilityArr.length > 0) {
          let arr = [];
          arr.push(item);
          // 判断是否存在该巡查点 facilityId组成新数组
          let idList = this.aboutFacilityArr.map(item => item.facilityNo);
          let organizationNo = this.aboutFacilityArr.map(
            item => item.organizationNo
          );
          // let lessee = this.aboutFacilityArr.map(item => item.lessee);
          if (organizationNo) {
            if (!organizationNo.includes(arr[0].organizationNo)) {
              //   //  当前点击设施组织·Id 等于当前登录的组织id 将需要添加设施组织Id 转化 为 设施组组织Id
              //   if (arr[0].organizationNo === JSON.parse(sessionStorage.organizationNo)) {
              //     arr[0].organizationNo = organizationNo[0]
              //   } else {
              this.$message.warning(`添加设施和设施组的组织机构不一致`);
              return;
              // }
            }
          }
          if (idList.includes(arr[0].facilityNo)) {
            this.$message.warning("该设施已经存在~");
            return;
          } else {
            this.aboutFacilityArr = JSON.parse(
              JSON.stringify(this.aboutFacilityArr.concat(item))
            );
          }
        } else {
          this.aboutFacilityArr = JSON.parse(
            JSON.stringify(this.aboutFacilityArr.concat(item))
          );
          return;
        }
      }
    },
    // 删除田块tag
    removeFacilityTag(facilityNo) {
      // if (this.nowChanceStau !== "edit" && this.topitemtypeid !== true) {
      //   return this.$message.error("点击修改按钮再进行编辑!");
      // }
      if (this.topitemtypeid === true) return;
      let index = this.aboutFacilityArr.indexOf(
        this.aboutFacilityArr.filter(d => d.facilityNo === facilityNo)[0]
      );
      this.aboutFacilityArr.splice(index, 1);
    },
    // 格式化数组
    resetFacilityArr() {
      const facilityMapperList = [];
      this.aboutFacilityArr.forEach(item => {
        const obj = {};
        obj["facilityNo"] = item.facilityNo;
        obj["facilityName"] = item.facilityName;
        facilityMapperList.push(obj);
      });
      return facilityMapperList;
    },
    faciStatus(e) {
      let title = "废弃设施组";
      if (this.topitemtypeid === true) {
        title = "恢复设施组";
      }
      this.$confirm("是否" + title, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          // console.log(222222222222222);
          if (e.groupStatus === false) {
            let status = false;
            let params = {
              facilityGroupNo: e.facilityGroupNo,
              groupStatus: status
            };
            this.divideInfo(params);
          } else if (e.groupStatus === true) {
            let status = true;
            let params = {
              facilityGroupNo: e.facilityGroupNo,
              groupStatus: status
            };
            this.divideInfo(params);
          }
          this.$nextTick(() => {
            setTimeout(() => {
              this.search();
            }, 300);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
          this.search();
          // this.resetActionBar();
        });
    },
    divideInfo(params) {
      landgroupInfoManage.editStatus(params).then(res => {
        if (res.code === 1) {
          return this.$message.success(res.msg || "修改成功!!!");
        } else return this.$message.warning(res.msg || "修改失败!!!");
      });
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    async handleEdit(row) {
      // TODO 点击行元素后 edit
      if (row.facilityGroupNo) {
        const { data: res } = await landgroupInfoManage.queryfacility(
          row.facilityGroupNo
        );
        if (res === undefined) {
          this.aboutFacilityArr = [];
        } else {
          this.aboutFacilityArr = res;
        }
      }
      this.formData = JSON.parse(JSON.stringify(row));
      this.facilityGroupNo = this.formData.facilityGroupNo;
      if (this.topitemtypeid === false) {
        this.editActive = true;
        this.saveActive = false;
        this.cancelActive = true;
        this.canInput = true;
      }
      this.searchFacility();
      this.openDialog("edit");
    },
    handleSelectionChange(list) {
      this.facilityGroupNoList = "";
      this.facilityGroupNoList = list.map(item => item.facilityGroupNo);
      if (this.topitemtypeid === false) {
        if (this.facilityGroupNoList.length > 0) this.delActive = true;
        else this.delActive = false;
      }
    },
    add() {
      this.canInput = true;
      this.nowChanceStau = "add";
      this.formData = {};
      this.aboutFacilityArr = [];
      this.addActive = false;
      this.delActive = false;
      this.saveActive = true;
      this.cancelActive = true;
      this.editActive = false;
      this.openDialog("add");
    },
    cancel(formData) {
      this.nowChanceStau = "";
      this.formData = {};
      this.image = "";
      this.aboutFacilityArr = [];
      this.canInput = false;
      this.addActive = true;
      this.delActive = false;
      this.saveActive = false;
      this.cancelActive = false;
      this.editActive = false;
      this.closeDialog();
      if (formData) {
        this.$refs[formData].resetFields();
      }
      this.$refs.tableData.setCurrentRow();
    },
    delmessage(e) {
      landgroupInfoManage
        .delListLandFGroupInfo(this.facilityGroupNoList)
        .then(res => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.search();
            this.resetActionBar();
            this.searchFacility();
          } else {
            this.$message.success(res.msg);
          }
        });
    },
    handleDelete(row) {
      // landgroupInfoManage.delListLandFGroupInfo([row.facilityGroupNo]).then(res => {
      //   if (res.code === 1) {
      //     this.$message.success(res.msg);
      //     this.search();
      //     this.resetActionBar();
      //     this.searchFacility();
      //   } else {
      //     this.$message.success(res.msg);
      //   }
      // });
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          landgroupInfoManage
            .delListLandFGroupInfo([row.facilityGroupNo])
            .then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg);
                this.search();
                this.resetActionBar();
                this.searchFacility();
              } else {
                this.$message.success(res.msg);
              }
            });
        })
        .catch(() => {
          //
          this.$message("取消删除");
        });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            // 编辑接口
            let facilityNoList = this.resetFacilityArr();
            this.formData.organizationNo = sessionStorage.organizationNo;
            this.formData.facilityNoList = facilityNoList.map(item => {
              return item.facilityNo;
            });
            landgroupInfoManage.editLandFGroupInfo(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.aboutFacilityArr = [];
                this.$refs[formData].resetFields();
                this.closeDialog();
                this.facilityArr = [];
                this.formData = {};
                this.facilityName = "";
                this.search();
                this.searchFacility();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            let facilityNoList = this.resetFacilityArr();
            this.formData.organizationNo = sessionStorage.organizationNo;
            this.formData.facilityNoList = facilityNoList.map(item => {
              return item.facilityNo;
            });
            // console.log(this.formData);
            // return
            // 新增接口
            landgroupInfoManage.addLandFGroupInfo(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                // this.closeDialog();
                this.aboutFacilityArr = [];
                this.facilityArr = [];
                this.formData = {};
                this.$refs[formData].resetFields();
                this.closeDialog();
                this.facilityName = "";
                this.searchFacility();
                this.search();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";
.pag {
  height: 100%;
  width: 100%;
  // border: 1px dashed rgba(14, 196, 151, 1);
  position: relative;
  padding: 40px 0;
}
.search-box {
  margin: 5px 0;
}
::v-deep .common-layout {
  .content {
    margin-bottom: 0 !important;
    height: calc(100% - 20px) !important;
    .pagination {
      right: 20px !important;
    }
    .table-box {
      height: 100% !important;
    }
    .form {
      height: 100% !important;
      padding: 3.5%;
    }
  }
}
.facility_arr {
  width: 100%;
  height: 150px;
  border: 1px solid #6ecae3;
  overflow-y: auto;
  padding-left: 10px;
}
.facility_title {
  text-align: start;
  margin-left: 15px;
  font-size: 10px;
  // color: rgba(255, 255, 255, 0.7);
}
.tags {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  .tag-item {
    height: 30px;
    padding: 5px 10px;
    background-color: #00a1c2;
    border-radius: 8px;
    display: flex;
    align-items: center;
    margin-top: 10px;
    margin-right: 10px;
    i {
      font-size: 14px;
    }
  }
}
::v-deep .el-form-item__label {
  min-width: 120px !important;
}
::v-deep .dell {
  span {
    color: red;
    border-bottom: 1px solid red;
  }
}
.point-name,
.close {
  color: #ffffff;
  padding: 2px;
}
</style>
